package repository

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	uuid "github.com/satori/go.uuid"
	"go_shengshu_admin/model"
	"go_shengshu_admin/query"
	"go_shengshu_admin/utils"
	"time"
)

type BannerRepository struct {
	DB *gorm.DB
}

type BannerRepoInterface interface {
	List(req *query.ListQuery) (users []*model.Banner, err error)
	GetTotal() (total int64, err error)
	GetBanner(banner model.Banner) (*model.Banner, error)
	ExistByBannerID(id string) *model.Banner
	Exist(banner model.Banner) *model.Banner
	Add(banner model.Banner) (*model.Banner, error)
	Edit(banner model.Banner) (bool, error)
	Delete(id string) (bool, error)
}

func (repo *BannerRepository) List(req *query.ListQuery) (banners []*model.Banner, err error) {
	db := repo.DB
	limit, offset := utils.Page(req.PageSize, req.Page)
	if err := db.Limit(limit).Offset(offset).Find(&banners).Error; err != nil {
		return nil, err
	}
	return banners, nil
}

func (repo *BannerRepository) GetTotal() (total int64, err error) {
	var users []model.Banner
	db := repo.DB
	if err := db.Find(&users).Count(&total).Error; err != nil {
		return 0, err
	}
	return total, nil
}

func (repo *BannerRepository) GetBanner(banner model.Banner) (*model.Banner, error) {
	if err := repo.DB.Where(&banner).Find(&banner).Error; err != nil {
		return nil, err
	}
	return &banner, nil
}

func (repo *BannerRepository) ExistByBannerID(id string) *model.Banner {
	var banner *model.Banner
	var count = 0
	repo.DB.Where("banner_id = ?", id).Find(&banner).Count(&count)
	if count > 0 {
		return banner
	}
	return nil
}

func (repo *BannerRepository) Exist(banner model.Banner) *model.Banner {
	if banner.Url != "" && banner.RedirectUrl != "" {
		var b model.Banner
		repo.DB.Model(&banner).Where("url= ? and redirect_url", banner.Url, banner.RedirectUrl).First(&b)
		return &b
	}
	return nil
}

func (repo *BannerRepository) Add(banner model.Banner) (*model.Banner, error) {
	exist := repo.Exist(banner)
	if exist != nil && exist.Url == banner.Url && exist.RedirectUrl == banner.RedirectUrl {
		return nil, fmt.Errorf("轮播已存在")
	}
	banner.BannerId = uuid.NewV4().String()
	banner.CreateAt, _ = time.Parse(utils.TimeLayout, utils.GetNow())
	banner.UpdateAt, _ = time.Parse(utils.TimeLayout, utils.GetNow())
	if err := repo.DB.Create(&banner).Error; err != nil {
		return nil, errors.New("轮播添加失败")
	}
	return &banner, nil
}

func (repo *BannerRepository) Edit(banner model.Banner) (bool, error) {
	if err := repo.DB.Model(&banner).Where("banner_id = ?", banner.BannerId).Updates(map[string]interface{}{
		"url": banner.Url, "redirect_url": banner.RedirectUrl,
	}).Error; err != nil {
		return false, err
	}
	return true, nil
}

func (repo *BannerRepository) Delete(id string) (bool, error) {
	if err := repo.DB.Where("banner_id = ?", id).
		Delete(&model.Banner{}).Error; err != nil {
		return false, err
	}
	return true, nil
}
